package com.st.warehouse.ui.navbar;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Handler;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.st.warehouse.R;
import com.st.warehouse.bean.Sign;
import com.st.warehouse.service.MyService;
import com.st.warehouse.ui.MainActivity;
import com.st.warehouse.ui.adapter.MyItemDecoration;
import com.st.warehouse.ui.adapter.YSignAppAdapter;
import com.st.warehouse.utils.Data;
import com.st.warehouse.utils.DialogUtils;
import com.st.warehouse.utils.LoadingDialog;
import com.st.warehouse.utils.PermissionChecker;
import com.st.warehouse.utils.RegexUtils;
import com.st.warehouse.utils.RetrofitUtil;
import com.st.warehouse.utils.SpinnerUtils;
import com.st.warehouse.utils.SystemUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 主页
 */
public class HomeFragment extends Fragment implements YSignAppAdapter.EventListener {
    private static HomeFragment homeFragment;
    private static String TAG = "HomeFragment";
    private TextToSpeech tts;//创建语音对象
    private View rootView;
    private TextView totalNum;
    private String totalNumStr = "0";
    private TextView signNum;
    private String signNumStr = "0";
    private String userOrder;
    private Spinner orderSpinner;
    private Button btn_add;
    private MyService myService;
    private EditText edit_content;
    private Button fresh_data;
    private Button voice_btn;
    private int pageIndex = 1;
    private int pageSize = 200;
    private RecyclerView phone_list;
    private YSignAppAdapter signAppAdapter;
    private boolean isScrolledToBottom = false;
    private long lastTriggerTime = 0;
    private static final long TRIGGER_INTERVAL = 1000; // 触发间隔为1秒
    private SwipeRefreshLayout swipeRefreshLayout;
    private LinearLayout ll_no_data;
    private LoadingDialog loadingDialog;//加载弹框
    private ArrayList<Sign> signList = new ArrayList<>();
    private SpeechRecognizer speechRecognizer;//语音识别
    protected static final int RESULT_SPEECH = 1;//语音识别请求码
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private EditText edit_phone;
    private EditText edit_name;


    public HomeFragment() {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();//关闭弹窗
        }
        if (speechRecognizer != null) {
            speechRecognizer.destroy();
            speechRecognizer = null;
        }
    }

    //单例创建
    public static HomeFragment getInstance(){
        if (homeFragment == null) {
            return new HomeFragment();
        }
        Log.d("test", "onCreateView:HomeFragment ");
        return homeFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null){
            rootView = inflater.inflate(R.layout.fragment_home, container, false);
            myService = RetrofitUtil.build(MyService.class);//初始化网络请求
            hideHeader();
            initView();
            initVice();
            getSignInList();
            spinnerDraw();
            listener();

        }
        return rootView;
    }

    /**
     * 权限列表
     */
    public static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,       // ***获取设备状态的权限，重要
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.INTERNET,
            "android.permission.BLUETOOTH_SCAN",
            "android.permission.BLUETOOTH_CONNECT",
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.READ_PHONE_STATE",
            "android.permission.USB_PERMISSION"
    };

    /**
     * 初始化语音权限
     */
    private void initVice() {
        // 检查并请求录音权限,申请权限
        PermissionChecker mPermissionChecker = new PermissionChecker(getContext());
        if (mPermissionChecker.judgePermissions(PERMISSIONS)) {
            ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, 0);
        } else {

        }

        SpeechRecognizer.isRecognitionAvailable(getActivity());
        // 初始化 SpeechRecognizer
        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(getActivity());
        // 设置监听器
        speechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle params) {
                Toast.makeText(getActivity(), "开始说话", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onBeginningOfSpeech() {
                // 开始说话
            }

            @Override
            public void onRmsChanged(float rmsdB) {
                // 音量变化
            }

            @Override
            public void onBufferReceived(byte[] buffer) {
                // 接收语音数据
            }

            @Override
            public void onEndOfSpeech() {
                Toast.makeText(getActivity(), "结束说话", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error) {
                String message;
                switch (error) {
                    case SpeechRecognizer.ERROR_AUDIO:
                        message = "音频错误";
                        break;
                    case SpeechRecognizer.ERROR_CLIENT:
                        message = "客户端错误";
                        break;
                    case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
                        message = "权限不足";
                        break;
                    case SpeechRecognizer.ERROR_NETWORK:
                        message = "网络错误";
                        break;
                    case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
                        message = "网络超时";
                        break;
                    case SpeechRecognizer.ERROR_NO_MATCH:
                        message = "没有匹配的识别结果";
                        break;
                    case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
                        message = "识别服务繁忙";
                        break;
                    case SpeechRecognizer.ERROR_SERVER:
                        message = "服务器错误";
                        break;
                    case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
                        message = "未检测到语音输入";
                        break;
                    default:
                        message = "未知错误";
                        break;
                }
                Toast.makeText(getActivity(), "识别错误：" + message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResults(Bundle results) {
                // 获取最终识别结果
                ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                if (matches != null && !matches.isEmpty()) {
                    if (edit_name != null && edit_name.hasFocus()) {
                        edit_name.append(matches.get(0)); // 显示识别结果
                        edit_name.setSelection(edit_name.getText().length()); // 光标移动到最后
                    }else if (edit_phone != null && edit_phone.hasFocus()) {
                        edit_phone.append(matches.get(0)); // 显示识别结果
                        edit_phone.setSelection(edit_phone.getText().length()); // 光标移动到最后
                    }else if (edit_content != null && edit_content.hasFocus()){
                        edit_content.append(matches.get(0)); // 显示识别结果
                        edit_content.setSelection(edit_content.getText().length()); // 光标移动到最后
                    }

                }
            }

            @Override
            public void onPartialResults(Bundle partialResults) {
                // 获取部分识别结果
                ArrayList<String> partialMatches = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                if (partialMatches != null && !partialMatches.isEmpty()) {
                    if (edit_name != null && edit_name.hasFocus()) {
                        edit_name.append(partialMatches.get(0)); // 显示识别结果
                        edit_name.setSelection(edit_name.getText().length()); // 光标移动到最后
                    }else if (edit_phone != null && edit_phone.hasFocus()) {
                        edit_phone.append(partialMatches.get(0)); // 显示识别结果
                        edit_phone.setSelection(edit_phone.getText().length()); // 光标移动到最后
                    }else if (edit_content != null && edit_content.hasFocus()){
                        edit_content.append(partialMatches.get(0)); // 显示识别结果
                        edit_content.setSelection(edit_content.getText().length()); // 光标移动到最后
                    }
                }
            }

            @Override
            public void onEvent(int eventType, Bundle params) {
                // 其他事件
            }
        });
    }

    private void spinnerDraw() {
        if (items.size() == 0){
            items.add("");
            items.add("1");
            items.add("2");
        }

        if (items != null && items.size() > 0){
            //下拉框
            SpinnerUtils.setupSpinner(getActivity(), orderSpinner, items, new SpinnerUtils.SpinnerListener() {
                @Override
                public void onItemSelected(int position) {
                    // 在这里处理下拉框选中项的逻辑

                }
            });
        }
    }

    private void hideHeader() {
        //状态栏设置
        getActivity().getWindow().setStatusBarColor(getActivity().getColor(R.color.transparent));
        getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//字体黑色
        // 隐藏 Activity 的 ActionBar
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
    }
    private void initView() {
        edit_content = rootView.findViewById(R.id.edit_content);
        fresh_data = rootView.findViewById(R.id.fresh_data);
        voice_btn = rootView.findViewById(R.id.voice_btn);
        phone_list = rootView.findViewById(R.id.phone_list);
        swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        ll_no_data = rootView.findViewById(R.id.ll_no_data);
        totalNum = rootView.findViewById(R.id.totalNum);
        totalNum.setText(totalNumStr);
        signNum = rootView.findViewById(R.id.signNum);
        signNum.setText(signNumStr);
        orderSpinner = rootView.findViewById(R.id.orderSpinner);
        btn_add = rootView.findViewById(R.id.btn_add);

        //

    }

    /**
     * 语音识别
     */
    private void startSpeechRecognition() {
        try {
            if (speechRecognizer == null) {
                Toast.makeText(getActivity(), "无法创建 SpeechRecognizer 实例", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "zh-CN"); // 设置为中文
            speechRecognizer.startListening(intent); // 开始监听
        } catch (Exception e) {
            DialogUtils.show(getActivity(),"暂无支持");
        }
    }

    /**
     * 二维码扫描结果
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case RESULT_SPEECH: {
                if (resultCode == RESULT_OK && null != data) {

                    ArrayList<String> text = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    DialogUtils.show(getActivity(),text.get(0));
                }
                break;
            }

        }

    }
    private static List<String> items = new ArrayList<>();
    private void listener() {

        //新增
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addName();
            }
        });

        //刷新
        fresh_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadDialog();
                pageIndex = 1;
                getSignInList();
            }
        });
        //语音
        voice_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startSpeechRecognition();
            }
        });

        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    pageIndex = 1;
                    signList.clear();
                    loadDialog();
                    getSignInList();// 执行刷新操作
                    swipeRefreshLayout.setRefreshing(false);// 停止刷新动画
                } catch (Exception e) {
                    e.printStackTrace();
                    if (loadingDialog != null && loadingDialog.isShowing()) {
                        loadingDialog.dismiss();//关闭弹窗
                    }
                    swipeRefreshLayout.setRefreshing(false);// 停止刷新动画
                }
            }
        });


        //滚动监听
        phone_list.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 当滚动停止时触发
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到最后
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (layoutManager != null) {
                        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                        int totalItemCount = layoutManager.getItemCount();

                        if (lastVisibleItemPosition == totalItemCount - 1) {
                            // 如果是最后一个可见 item
                            isScrolledToBottom = true;
                        } else {
                            isScrolledToBottom = false;
                        }
                    }

                    // 判断是否满足触发条件
                    long currentTime = System.currentTimeMillis();
                    if (isScrolledToBottom && currentTime - lastTriggerTime >= TRIGGER_INTERVAL) {
                        Log.d(TAG, "onConfirm: ");
                        pageIndex = pageIndex + 1;
                        Log.d(TAG, "pageIndex: "+pageIndex);
                        getSignInList();  // 执行数据请求
                        lastTriggerTime = currentTime;  // 更新触发时间
                    }
                }
            }

        });

        //文本复制

    }

    /**
     * 添加签到账号
     */
    private void addName() {
        // 如果 view1 已经有父视图，先移除它
        View view1 = getLayoutInflater().inflate(R.layout.dialog_add_name, null);
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setView(view1);
        final AlertDialog dialog2 = dialog.create();
        dialog2.show();

        //=====================================版本组件==============================
        edit_phone = view1.findViewById(R.id.edit_userPhone);
        edit_name = view1.findViewById(R.id.edit_name);
        EditText edit_order = view1.findViewById(R.id.edit_order);//
        Button btn_speach1 = view1.findViewById(R.id.btn_speach1);//语音1
        Button btn_cancel = view1.findViewById(R.id.btn_cancel);//取消
        Button btn_ok = view1.findViewById(R.id.btn_ok);//确认
        myService = RetrofitUtil.build(MyService.class);//初始化网络请求


        //取消
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setClickableWithDelay(btn_cancel, 1000);//按钮禁止连点
                dialog2.dismiss();
            }
        });

        //确认
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setClickableWithDelay(btn_ok, 1000);//按钮禁止连点
                String userName = edit_name.getText().toString();
                String phoneNo = edit_phone.getText().toString();
                if (Data.isNull(phoneNo)) {
                    DialogUtils.show(getActivity(), "请输入手机号");
                    return;
                }
                if (RegexUtils.isPhoneInvalid(phoneNo)) {
                    DialogUtils.show(getActivity(), "请输入正确的手机号");
                    return;
                }
                if (Data.isNull(userName)) {
                    DialogUtils.show(getActivity(), "请输入姓名");
                    return;
                }

                Integer orderNum = edit_order.getText().toString().isEmpty() ? 99 : Integer.parseInt(edit_order.getText().toString());
                //新增
                myService.addName(phoneNo,userName,orderNum).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.isSuccessful()) {
                                JSONObject data = RetrofitUtil.getDataFromResponse(response);
                                if (200 == data.getInteger("code")) {
                                    DialogUtils.show(getActivity(), "新增成功");
                                    getSignInList();
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                        SystemUtils.invokeHttpError((Activity) getActivity(), throwable.getMessage());
                    }
                });
                dialog2.dismiss();

            }
        });

        btn_speach1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startSpeechRecognition(); //开始语音识别
            }
        });


    }

    private Handler mHandler = new Handler();
    //按钮禁止连点
    public void setClickableWithDelay(final View button, long delay) {
        button.setClickable(false);
        //button.setBackground(getActivity().getDrawable(R.drawable.background_gradient_blue_btn2));
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    button.setClickable(true);
                    //button.setBackground(getActivity().getDrawable(R.drawable.background_gradient_blue_btn1));
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                }
            }
        }, delay);
    }

    private void loadDialog() {
        //加载弹窗
        LoadingDialog.Builder loadBuilder = new LoadingDialog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true)//返回键是否可点击
                .setCancelOutside(false);//窗体外是否可点击
        loadingDialog = loadBuilder.create();
        loadingDialog.show();//显示弹窗
    }

    //查询数据
    private void getSignInList(){
        String content = edit_content.getText().toString();
        String searchContent = "";
        if (!Data.isNull(content)){
            searchContent = content;
        }
        Object selectedItem = orderSpinner.getSelectedItem();
        if (selectedItem != null){
            String orderSpinnerItem = orderSpinner.getSelectedItem().toString();
            userOrder = orderSpinnerItem;
        }
        myService.getSignInList(pageIndex,pageSize,searchContent, userOrder).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.isSuccessful()){
                        JSONObject data = RetrofitUtil.getDataFromResponse(response);
                        if (200 == data.getInteger("code")){
                            JSONObject json = data.getJSONObject("data");
                            JSONArray list = Data.getJSONArray(json, "list", new JSONArray());
                            JSONArray userOrders = Data.getJSONArray(json, "userOrders", new JSONArray());

                            if (list != null && list.size() > 0){
                                ll_no_data.setVisibility(View.GONE);
                                swipeRefreshLayout.setVisibility(View.VISIBLE);

                                // 手动遍历 JSONArray，将元素添加到 List<String> 中
                                List<String> userOrderList = new ArrayList<>();
                                userOrderList.add("");
                                for (int i = 0; i < userOrders.size(); i++) {
                                    userOrderList.add(userOrders.getString(i));  // 获取每个 String 类型的元素
                                }
                                items = userOrderList;
                                //
                                signList = new ArrayList<>();
                                int sum = list.size();//总条数
                                int temp = 0;//今日已签到总数
                                for (int i = 0; i < list.size(); i++) {
                                    Sign bean = JSON.parseObject(list.getString(i), Sign.class);
                                    // 解析为日期对象，使用合适的格式
                                    Date date = DateUtil.parse(bean.getFreshTime(), "yyyy-MM-dd'T'HH:mm:ss.SSSZ");
                                    String formattedDate = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
                                    bean.setFreshTime(formattedDate);
                                    //
                                    boolean isCurrentDay = DateUtil.isSameDay(date, new Date());
                                    if (1 == bean.getIsSign() && isCurrentDay){
                                        bean.setSignInfo("今日已签到");
                                        temp += 1;
                                    }else {
                                        bean.setSignInfo("今日未签到");
                                    }
                                    signList.add(bean);

                                }

                                signNum.setText(String.valueOf(temp));
                                totalNum.setText(String.valueOf(sum));
                                spinnerDraw();
                                onloadRecyclerView(signList);
                            }else {
                                pageIndex = 1;
                            }

                            if (signList.size() == 0){
                                ll_no_data.setVisibility(View.VISIBLE);
                                swipeRefreshLayout.setVisibility(View.GONE);
                            }
                        }
                    }
                    if (loadingDialog != null && loadingDialog.isShowing()) {
                        loadingDialog.dismiss();//关闭弹窗
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    if (loadingDialog != null && loadingDialog.isShowing()) {
                        loadingDialog.dismiss();//关闭弹窗
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                System.out.println(throwable.getMessage());
                if (loadingDialog != null && loadingDialog.isShowing()) {
                    loadingDialog.dismiss();//关闭弹窗
                }
                SystemUtils.invokeHttpError(getActivity(), throwable.getMessage());
            }
        });
    }

    //渲染数据
    private void onloadRecyclerView(ArrayList<Sign> signList) {
        if (null == signAppAdapter){
            signAppAdapter = new YSignAppAdapter(signList, getActivity());
            phone_list.setLayoutManager(new LinearLayoutManager(getActivity()));
            phone_list.setAdapter(signAppAdapter);
            signAppAdapter.setEventListener(this);
            int horizontalMargin = 16; // 假设左右边距为16dp
            int verticalMargin = 16;   // 假设上下外部边距为32dp
            phone_list.addItemDecoration(new MyItemDecoration(horizontalMargin,verticalMargin));
        }else {
            if (pageIndex == 1) {
                signAppAdapter.setData(signList);
            }else {
                signAppAdapter.addData(signList);
            }
            signAppAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d("onDetach", "onDetach: HomeFragment");
    }
    //修改姓名成功
    @Override
    public void updateSuccess() {
        getSignInList();
    }
}